<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
    <link href="lib/mapbox-gl2.6.1.css" rel="stylesheet">
    <script src="lib/mapbox-gl2.6.1.js"></script>
    <script src="lib/jquery-3.6.0.min.js"></script>
    <script src='lib/mapbox-gl-language.js'></script>
    <script src="lib/dat.gui.min.js"></script>

    <style>
        body {
            margin: 0;
            padding: 0;
        }

        #map {
            position: absolute;
            top: 0;
            bottom: 0;
            width: 100%;
        }
    </style>
</head>

<body>
    <div id="map"></div>

    <script>
        /** 面图层geojson数值分布，全省建议到乡，分市到村 */
        mapboxgl.accessToken = 'pk.eyJ1IjoiaG91eGlleXUiLCJhIjoiY2pldjE5amU3NndzeDM5bzd5bm9ncDgycyJ9.j1F-Lgid3L5k2Abm8_xTeQ';
        const map = new mapboxgl.Map({
            container: 'map',
            style: 'mapbox://styles/mapbox/dark-v10',
            center: [117.974103, 36.374436],
            zoom: 7
        });
        map.addControl(
            new MapboxLanguage({
                defaultLanguage: "zh-Hans",
            })
        );
        map.on('load', async () => {

            // Add a geojson point source.
            // Heatmap layers also work with a vector tile source.
            let ip1 = '192.168.0.53:8080';
            let ipapi = '6ql20nip.ipyingshe.net';
            let level = 'xiang'
            let field = 'f176'
            //县级4.6M，乡级20M(39s)
            let url2 = `http://${ip1}/geoserver/rp7/ows?service=WFS&version=1.0.0&request=GetFeature&outputFormat=application/json&typeName=rp7:gv_${level}&propertyName=geom,area,codename,${field}&format_options=id_policy:reference_no=false`

            //可抽稀，0.001精度，县级2M，乡级7M(25s),村级14M
            // let url3 = `http://${ip1}/features?areacode=&field=${field}&level=${level}&simplify=0.001`
            let geodata = await $.getJSON(url2);
            // console.log(geodata.features.map(f => f.properties.f176  / f.properties.area))
            let minmax = await $.getJSON(`http://${ipapi}/getminmax?field=${field}&level=${level}`);
            // console.log(minmax);
            let min = minmax.min;
            let max = minmax.max;
            var options = {
                'title': '人口分布',
                color1: '#51bbd6',
                val1: min + (max - min) / 3,
                color2: '#f1f075',
                val2: max - (max - min) / 3,
                color3: '#f28cb1',
                min:min,
                max:max
            };

            /** 参数配置组件 */
            initOptions(map, options);

            // console.log(max, geodata.features)
            // console.log(geodata)
            map.addSource('bj', {
                'type': 'geojson',
                'data': geodata,
                // promoteId:'code'
                generateId: true
            });

            // Add a layer showing the state polygons.
            map.addLayer({
                'id': 'states-layer',
                'type': 'fill',
                'source': 'bj',
                'paint': {
                    'fill-color': [
                        'step',
                        ['get', 'f176'],
                        options.color1,
                        options.val1,
                        options.color2,
                        options.val2,
                        options.color3
                    ],
                    // 'fill-outline-color': 'rgba(200, 100, 240, 1)'
                }
            });

            const popup = new mapboxgl.Popup({
                closeButton: false
            });

            map.addLayer({
                'id': 'states-highlighted',
                'type': 'fill',
                'source': 'bj',
                'paint': {
                    'fill-outline-color': '#484896',
                    'fill-color': '#6e599f',
                    'fill-opacity': 0.75
                },
                'filter': ['==', ['id'], '']
            }
            );
            map.addLayer({
                id: "label_buildings",
                type: "symbol",
                source: "bj",
                layout: {
                    "text-field": "{codename}",
                    // "text-font": ["DIN Offc Pro Medium", "Arial Unicode MS Bold"],
                    "text-size": 10,
                    "text-offset": [0, -1.5],
                    // "text-allow-overlap": true
                },
                paint: {
                    "text-halo-width": 1,
                    "text-halo-color": "white",
                },
            });
            map.on('mousemove', 'states-layer', (e) => {
                // Change the cursor style as a UI indicator.
                map.getCanvas().style.cursor = e.features.length ? 'pointer' : '';

                popup.setLngLat(e.lngLat)
                    .setHTML(`<b>${e.features[0].properties.codename}</b><br>人口数：${e.features[0].properties.f176}<br>面积：${(e.features[0].properties.area).toFixed(2)}平方公里<br>人口密度：${(e.features[0].properties.f176  / e.features[0].properties.area).toFixed(2)}人/km`)
                    .addTo(map);

                map.setFilter('states-highlighted', ['==', ['id'], e.features[0].id]);
            });

            map.on('mouseleave', 'states-layer', () => {
                map.getCanvas().style.cursor = '';
                popup.remove();
                map.setFilter('states-highlighted', ['==', ['id'], '']);
            });
        });

        function initOptions(map, options) {
            // var Options = function () 
            var gui = new dat.GUI();

            gui.add(options, 'title');
            var ctlcolor1 = gui.addColor(options, 'color1');
            var ctlval1 = gui.add(options, 'val1').min(options.min).max(options.max);
            var ctlcolor2 = gui.addColor(options, 'color2');
            var ctlval2 = gui.add(options, 'val2').min(options.min).max(options.max);
            var ctlcolor3 = gui.addColor(options, 'color3');

            function refresh() {
                map.setPaintProperty('states-layer', 'fill-color', [
                    'step',
                    ['get', 'f176'],
                    options.color1,
                    options.val1,
                    options.color2,
                    options.val2,
                    options.color3
                ])
            }

            ctlcolor1.onChange(function (value) {
                refresh();
            });
            ctlcolor2.onChange(function (value) {
                refresh();
            });
            ctlcolor3.onChange(function (value) {
                refresh();
            });
            ctlval1.onChange(function (value) {
                refresh();
            });
            ctlval2.onChange(function (value) {
                refresh();
            });
        }
    </script>

</body>

</html>